package com.bianmaba.hive;

import java.sql.SQLException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.DriverManager;

/**
 * 问题：xxx_user is not allowed to impersonate hive
 * 服务器需要配置：hadoop/etc/hadoop/core-site.xml，添加如下配置信息
 * <property>
 * <name>hadoop.proxyuser.root.groups</name>
 * <value>*</value>
 * </property>
 * <property>
 * <name>hadoop.proxyuser.root.hosts</name>
 * <value>*</value>
 * </property>
 * <p>
 * <p>
 * 问题：现服务器无法连接时：Connection refused
 * 服务器需要运行（注意启动顺序,启动时间可能比较长），也可以去掉nohup 以观查状态
 * metastore:nohup hive --service metastore &
 * hiveserver2:nohup hive --service hiveserver2 &
 * <p>
 * 启动成功后执行：netstat -ntulp |grep 10000  可以看到类似如下信息
 * tcp 0 0 0.0.0.0:10000 0.0.0.0:* LISTEN xxxxx/java
 * <p>
 * 使用beeline连接hiveserver2
 * beeline -u jdbc:hive2://192.168.1.10:10000/default
 * default:表示数据库
 */
public class HiveJdbc {

    private static String driverName = "org.apache.hive.jdbc.HiveDriver";

    public static void main(String[] args)
            throws SQLException {
        try {
            Class.forName(driverName);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            System.exit(1);
        }

        Connection con = DriverManager.getConnection(
                "jdbc:hive2://192.168.1.10:10000/default", "root", "root");
        Statement stmt = con.createStatement();
        String tableName = "test";
        stmt.execute("drop table if exists " + tableName);
        stmt.execute("create table " + tableName +
                " (id int, name string)");
        System.out.println("Create table success!");
        // show tables
        String sql = "show tables '" + tableName + "'";
        System.out.println("Running: " + sql);
        ResultSet res = stmt.executeQuery(sql);
        if (res.next()) {
            System.out.println(res.getString(1));
        }
        // show tables
        sql = "show databases";
        System.out.println("Running: " + sql);
        res = stmt.executeQuery(sql);
        if (res.next()) {
            System.out.println(res.getString(1));
        }


        // describe table
        sql = "describe " + tableName;
        System.out.println("Running: " + sql);
        res = stmt.executeQuery(sql);
        while (res.next()) {
            System.out.println(res.getString(1) + "\t" + res.getString(2));
        }


        sql = "select * from " + tableName;
        res = stmt.executeQuery(sql);
        while (res.next()) {
            System.out.println(String.valueOf(res.getInt(1)) + "\t"
                    + res.getString(2));
        }

        sql = "select count(1) from " + tableName;
        System.out.println("Running: " + sql);
        res = stmt.executeQuery(sql);
        while (res.next()) {
            System.out.println(res.getString(1));
        }
    }
}